package ntu.metaweb.storage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import ntu.metaweb.XMLMarshaller;
import ntu.p2p.dht.DHTContentKey;

public class WebPageQueryKey implements DHTContentKey {

	private static final long serialVersionUID = 1677103299631289158L;

	private Id id;
	private URL url;
	
	public static WebPageQueryKey build (InputBuffer buf, Endpoint endpoint)
			throws IOException {
		return new WebPageQueryKey(buf, endpoint);
	}
	
	public WebPageQueryKey(String url, String query) {
		try {
			this.url = new URL(url + query);
			String temp = "query_" + this.url.toExternalForm();
			this.id = rice.pastry.Id.build(temp.getBytes());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public WebPageQueryKey(URL url) {
		this.url = url;
		String temp = "query_" + this.url.toExternalForm();
		this.id = rice.pastry.Id.build(temp.getBytes());
	}
	
	protected WebPageQueryKey(InputBuffer buf, Endpoint endpoint) 
			throws IOException {
		this.id = endpoint.readId(buf, buf.readShort());
		this.url = (URL) XMLMarshaller.getInstance().unmarshall(buf.readUTF());
	}
	
	@Override
	public Id getId() {
		return id;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		buf.writeShort(this.id.getType());
		this.id.serialize(buf);
		buf.writeUTF(XMLMarshaller.getInstance().marshall(url));
	}
	
	public int hashCode() {
		return id.hashCode() + url.hashCode();
	}
	
	public boolean equals(Object o) {
		if ((o == null) || !(o instanceof WebPageQueryKey))
			return false;
		WebPageQueryKey key = (WebPageQueryKey) o;
		return this.id.equals(key.id) && this.url.equals(key.url);
	}
	
	public String toString() {
		return url.toExternalForm();
	}
}
